﻿using Microsoft.Extensions.DependencyInjection;
using Modules.Payroll.Repositories;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.Exceptions;

namespace Modules.Payroll;


/// <summary>
/// 工资单设置服务
/// </summary>
[UseDI(ServiceLifetime.Scoped)]
public class WagePayrollSettingService
{
    private readonly WagePayrollSettingRepository wagePayrollSettingRepository;
    private readonly IApplicationContext applicationContext;

    public WagePayrollSettingService(WagePayrollSettingRepository wagePayrollSettingRepository, IApplicationContext applicationContext)
    {
        this.wagePayrollSettingRepository = wagePayrollSettingRepository;
        this.applicationContext = applicationContext;
    }

    /// <summary>
    /// 工资单设置表单详情
    /// </summary>
    /// <param name="id">主键</param>
    /// <returns></returns>
    public WagePayrollSetting? Get(int id)
    {
        return wagePayrollSettingRepository.Get(id);
    }

    /// <summary>
    /// 批量删除，根据id
    /// </summary>
    /// <param name="ids">id的集合</param>
    public void Deleted(IEnumerable<int> ids)
    {
        foreach (int id in ids)
        {
            Delete(id);
        }
    }

    /// <summary>
    /// 单个删除
    /// </summary>
    /// <param name="id">主键</param>
    public void Delete(int id)
    {
        wagePayrollSettingRepository.DeleteByEntityId(id);
    }

    /// <summary>
    /// 创建工资单设置
    /// </summary>
    /// <param name="entity">实体对象</param>
    public void Create(WagePayrollSetting entity)
    {
        wagePayrollSettingRepository.Insert(entity);
    }

    /// <summary>
    /// 编辑工资单设置
    /// </summary>
    /// <param name="entity">实体对象</param>
    public void Update(WagePayrollSetting entity)
    {
        wagePayrollSettingRepository.Update(entity);
    }

    public IEnumerable<WagePayrollSetting> GetAll()
    {
        return wagePayrollSettingRepository.GetAll();
    }

    public void Save(IEnumerable<WagePayrollSetting> entitys)
    {
        try
        {
            applicationContext.Transaction.Begin();
            //删除所有设置
            IEnumerable<WagePayrollSetting> wagePayrollSettings = GetAll();
            foreach (var item in wagePayrollSettings)
            {
                wagePayrollSettingRepository.Delete(item);
            }
            foreach (var item in entitys)
            {
                Create(item);
            }
            applicationContext.Transaction.Complete();
        }
        catch (Exception ex)
        {
            applicationContext.Transaction.Abort();
            throw new BusinessException($"工资单信息设置失败");
        }
    }
}